﻿using BtLabelModel;
using BtLabelTool;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Media;

namespace BtLabelBLL
{
    public class ChannelUartBLL
    {
        public SerialPort _port;
        public RichTextBox _RichTextBoxInfo;
        /// <summary>
        /// 一发一收
        /// </summary>
        /// <param name="sendbyte">发送字节</param>
        /// <param name="delay">返回超时</param>
        /// <param name="wait">返回等待</param>
        /// <returns>返回</returns>
        public string SendGetStr(byte[] sendbyte, int delay = 3000, int wait = 500)
        {
            try
            {
                //发送
                PortHelper.SendData(_port, sendbyte);
                //写日志
                string senddata = DateTime.Now.ToString("HH:mm:ss.fff") + "\r\nSend:" + CommonHelper.GetByteStr(sendbyte);
                UiBLL.RichTextBoxAppendText(_RichTextBoxInfo, Brushes.SteelBlue, senddata);
                //读取返回
                string recievestr = PortHelper.GetData(_port, delay, wait);
                //写日志
                string recievedata = DateTime.Now.ToString("HH:mm:ss.fff") + "\r\nRecieve:" + recievestr;
                UiBLL.RichTextBoxAppendText(_RichTextBoxInfo, Brushes.SteelBlue, recievedata);
                return recievestr;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取Mac地址
        /// </summary>
        /// <param name="mac"></param>
        /// <returns></returns>
        public bool GetMac(ref string mac,ref string err)
        {
            try
            {
                DateTime timeOut = DateTime.Now.AddMilliseconds(5500);
            label2:
                _port.DiscardInBuffer();
                _port.DiscardOutBuffer();
                string recievestr = SendGetStr(PortModel.ChannelUartModel.GetMac, 2000, 300);
            label1:
                if (recievestr.Contains("mac=") == false)
                {
                    //未接收到返回再次发送
                    if (recievestr == "")
                    {
                        if (DateTime.Now > timeOut)
                        {
                            err = "null";
                            return false;
                        }
                        goto label2;
                    }
                    else
                    {
                        //返回的不是mac继续读取返回值
                        recievestr = PortHelper.GetData(_port, 2000, 100);
                        //写日志
                        string recievedata = DateTime.Now.ToString("HH:mm:ss.fff") + "\r\nRecieve:" + recievestr;
                        UiBLL.RichTextBoxAppendText(_RichTextBoxInfo, Brushes.SteelBlue, recievedata);
                        goto label1;
                    }
                }
                //解析mac地址
                int index = recievestr.LastIndexOfAny(new char[] { 'm', 'a', 'c', '=' }) + 1;
                mac = recievestr.Substring(index, 2) + " "
                    + recievestr.Substring(index + 2, 2) + " "
                    + recievestr.Substring(index + 4, 2) + " "
                    + recievestr.Substring(index + 6, 2) + " "
                    + recievestr.Substring(index + 8, 2) + " "
                    + recievestr.Substring(index + 10, 2);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 点灯
        /// </summary>
        /// <returns></returns>
        public bool LightRgb()
        {
            try
            {
                //发送命令
                string recievestr = SendGetStr(PortModel.ChannelUartModel.LightRgb,1000,500);
                //判断结果
                if (recievestr.Equals(PortModel.ChannelUartModel.LightRgbOk) == false)
                {
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 生成刷入图片
        /// </summary>
        /// <param name="temp">图片类型</param>
        /// <param name="mac">mac地址</param>
        /// <returns></returns>
        public string CreatePic(string temp,string mac)
        {
            try
            {
                string path = "";
                if (temp == "QR")
                {
                    //二维码图片
                    path = Environment.CurrentDirectory + "\\" + mac+ ".png";
                    ProductBLL.CreateQrCode(mac, path);
                }
                if (temp == "BlackRed")
                {
                    //红黑图片
                    path = Environment.CurrentDirectory + "\\BaseBlackRed.png";
                }
                return path;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取图片像素实体
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="bitmapstr">二进制流</param>
        /// <returns></returns>
        public System.Drawing.Bitmap GetBitMap(string path,ref string bitmapstr)
        {
            try
            {
                System.Drawing.Bitmap bitmap = (System.Drawing.Bitmap)System.Drawing.Image.FromFile(path).Clone();
                //获取二进制流
                MemoryStream ms = new MemoryStream();
                bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Flush();
                ms.Close();
                bitmapstr = Convert.ToBase64String(arr);
                //旋转
                bitmap.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone);
                return bitmap;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 刷入图片
        /// </summary>
        /// <param name="bitmap">像素图</param>
        /// <param name="barDelay">包发送等待</param>
        /// <returns></returns>
        public bool WritePic(System.Drawing.Bitmap bitmap,int barDelay)
        {
            try
            {
                //读取红黑像素
                byte[] redByte = ProductBLL.BitmapArgbToByte(bitmap, 152, 296, 2);
                byte[] blackByte = ProductBLL.BitmapArgbToByte(bitmap, 152, 296, 0);
                byte[] bmpByte = blackByte.Concat(redByte).ToArray();
                //压缩图片
                List<JsonModel.BarModel> bars = ProductBLL.GetCompressData(bmpByte);
                //刷图命令
                UiBLL.RichTextBoxAppendText(_RichTextBoxInfo, Brushes.Blue, "发送刷图命令");
                string recievestr = SendGetStr(PortModel.ChannelUartModel.SendPic((byte)bars.Count()));
                if (recievestr.Contains(PortModel.ChannelUartModel.SendPicOk) == false)
                {
                    UiBLL.RichTextBoxAppendText(_RichTextBoxInfo, Brushes.Tomato, "发送刷图命令失败");
                    return false;
                }
                //发送图片数据
                for (int i = 1; i < bars.Count+1; i++)
                {
                    //head
                    UiBLL.RichTextBoxAppendText(_RichTextBoxInfo, Brushes.Blue, "第" + i + "个包");
                    recievestr = SendGetStr(PortModel.ChannelUartModel.SendBarHead((byte)i, bars[i - 1].CompressByte.Length));
                    if (recievestr.Contains(PortModel.ChannelUartModel.SendBarHeadOk) == false)
                    {
                        UiBLL.RichTextBoxAppendText(_RichTextBoxInfo, Brushes.Tomato, "发送蓝牙数据命令失败");
                        return false;
                    }
                    //data
                    recievestr = SendGetStr(bars[i - 1].CompressByte, 3000, barDelay * 1000);
                    if (recievestr.Contains(PortModel.ChannelUartModel.SendBarDataOk) == false)
                    {
                        UiBLL.RichTextBoxAppendText(_RichTextBoxInfo, Brushes.Tomato, "发送图像数据失败");
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 进入低功耗
        /// </summary>
        /// <returns></returns>
        public bool InLowPower()
        {
            try
            {

                UiBLL.RichTextBoxAppendText(_RichTextBoxInfo, Brushes.Blue, "进入低功耗");
                string recievestr = SendGetStr(PortModel.ChannelUartModel.SetLowPower);
            label2:
                if (recievestr.Contains(PortModel.ChannelUartModel.SetLowPowerOk) == false)
                {
                    //未接收到返回
                    if (recievestr == "")
                    {
                        UiBLL.RichTextBoxAppendText(_RichTextBoxInfo, Brushes.Blue, "进入低功耗失败");
                        return false;
                    }
                    else
                    {
                        //返回的是日志继续读取返回值
                        recievestr = PortHelper.GetData(_port, 5000, 1000);
                        //写日志
                        string recievedata = DateTime.Now.ToString("HH:mm:ss.fff") + "\r\nRecieve:" + recievestr;
                        UiBLL.RichTextBoxAppendText(_RichTextBoxInfo, Brushes.SteelBlue, recievedata);
                        goto label2;
                    }
                }
                UiBLL.RichTextBoxAppendText(_RichTextBoxInfo, Brushes.Blue, "进入低功耗成功");
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }
}
